<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hypref_mall
 * contact  hyperf_mall@163.com
 */
namespace App\Repository;

use App\Constants\BalanceConstants;
use App\Exception\BaseException;
use App\Model\MemberBalanceModel;
use App\Utils\DB;
use App\Utils\Log;
use Hyperf\Di\Annotation\Inject;
use Swoole\Exception;

class MemberBalanceRepository extends BaseRepository
{
    /**
     * @Inject
     * @var MemberBalanceModel
     */
    protected $model;

    /**
     * @Inject
     * @var MemberBalanceLogRepository
     */
    protected MemberBalanceLogRepository $memberBalanceLogRepository;

    /**
     * Notes:加余额
     * Author: Bruce.z
     * DateTime: 2022/8/22 10:42
     * @param int $member_id
     * @param float $money
     * @return int
     */
    public function incMoney(int $member_id, float $money): int
    {
        $info =  $this->_searchFactor(['member_id'=>$member_id])->first();
        if(empty($info)){
            $this->baseAdd(['member_id' => $member_id]);
        }

        return $this->_searchFactor(['member_id'=>$member_id])->increment(
            'total_money',
            $money,
            ['enable_balance' => DB::raw("enable_balance + $money")]
        );
    }

    /**
     * Notes: 减余额
     * Author: Bruce.z
     * DateTime: 2022/8/22 10:42
     * @param int $member_id
     * @param float $money
     * @return int
     */
    public function decMoney(int $member_id, float $money): int
    {
        $info =  $this->_searchFactor(['member_id'=>$member_id])->first();
        if(empty($info)){
            $this->baseAdd(['member_id' => $member_id]);
        }

        return $this->_searchFactor(['member_id'=>$member_id])->decrement(
            'total_money',
            $money,
            ['enable_balance' => DB::raw("enable_balance + $money")]
        );
    }

    /**
     * Notes: 售后单退款
     * Author: Bruce.z
     * DateTime: 2022/8/22 11:16
     * @param int $member_id
     * @param float $money
     * @param string $oid
     * @return bool
     */
    public function afterMoney(int $member_id, float $money, string $oid): bool
    {
        DB::beginTransaction();
        try {
            $this->incMoney($member_id, $money);
            $log = [
                'member_id'=>$member_id,
                'type'=>BalanceConstants::TYPE_INC,
                'profit_type'=>BalanceConstants::PROFIT_TYPE_ORDER_SALE,
                'price'=>$money,
                'desc'=>'订单：' . $oid . ' 退款到余额',
            ];
            $this->memberBalanceLogRepository->baseAdd($log);
            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            Log::getInstance()->error('退款失败',[$e->getMessage()]);
            //throw new BaseException(BaseException::BASE_ERROR, $e->getMessage());
            return false;
        }

        return true;
    }
}
